package com.sanxiang.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sanxiang.common.CommonResult;
import com.sanxiang.entity.ManagerTable;
import com.sanxiang.mapper.ManagerTableMapper;
import com.sanxiang.service.RedisService;
import com.sanxiang.utils.TokenUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/manager")
public class LoginController {


    @Resource
    private ManagerTableMapper managerTableMapper;

    @Resource
    private RedisService redisService;


    @PostMapping("/login")
    public CommonResult login(@RequestBody ManagerTable manager) {
        ManagerTable managerTable = managerTableMapper.selectByName(manager.getManagerName());

        QueryWrapper<ManagerTable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("manager_name", manager.getManagerName());
        queryWrapper.eq("manager_password", manager.getManagerPassword());

        ManagerTable res = managerTableMapper.selectOne(queryWrapper);

        // 判断密码是否正确
        if (!manager.getManagerPassword().equals(managerTable.getManagerPassword())) {
            return CommonResult.validateFailed("密码错误");
        }
        if (res == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        String token = TokenUtil.sign(managerTable.getManagerId());
        // 存入token到redis
        redisService.set(String.valueOf(managerTable.getManagerId()), token);

        return CommonResult.success(token);
    }

}
